package com.kingbook.services;

import com.kingbook.core.base.SupportService;
import com.kingbook.core.result.JSONResult;
import com.kingbook.entity.Tons;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author Bucky
 * @Date 2020-02-16 21:22:21
 * @Version 1.0
 */
@Slf4j
@Service
public class TonsService extends SupportService {

    @PostConstruct
    private void init() {
        setNamespace("Tons");
    }

    public JSONResult updateTons(Map<String, Object> param) {
        int mid = MapUtils.getIntValue(param, "mid");
        int id = MapUtils.getIntValue(param, "id");
        int tons = MapUtils.getIntValue(param, "tons");
        int jib = MapUtils.getIntValue(param, "jib");
        Tons ton = queryByTons(mid, tons, jib);
        if (ton != null && ton.getId() != id && ton.getTons() == tons && ton.getJib() == jib)
            return JSONResult.failed(tons + "T " + (jib > 0 ? jib + "节臂" : "") + " 已存在");
        return id > 0 ? modify(param) : save(param);
    }

    public void updateTonsName(int mid, int tons, int jib, int amount) {
        Map<String, Object> param = Maps.newHashMap();
        param.put("mid", mid);
        param.put("tons", tons);
        param.put("jib", jib);
        if(amount > 0) {
            param.put("amount", amount);
            param.put("amountHalf", amount/2);
            param.put("remarks", "8小时");
        }
        updateTons(param);
    }

    private Tons queryByTons(int mid, int tons, Integer jib) {
        Map<String, Object> param = new HashMap<>(4);
        param.put("mid", mid);
        param.put("tons", tons);
        param.put("jib", jib);
        return findObject("query", param, Tons.class);
    }

}
